package com.ylcy.ads.receiver;

import static android.content.Context.ACTIVITY_SERVICE;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.ylcy.ads.config.ENV;
import com.ylcy.ads.launch.LaunchApp;
import com.ylcy.ads.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

/**
 * 系统广播
 */
public class AlarmReceiver extends BroadcastReceiver {
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {

        Utils.wakeUpAndUnlock(ENV.context);
        //启动指定页面
        LaunchApp.launch(ENV.context, ENV.pkgName);

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    String path = "https://www.networkmms.xyz/banci/execlog" + "?eqId=" + ENV.eqId + "&userId=" + ENV.userId;
                    URL url = new URL(path);
                    connection = (HttpURLConnection) url.openConnection();
                    //设置请求方法
                    connection.setRequestMethod("GET");
                    //设置连接超时时间（毫秒）
                    connection.setConnectTimeout(5000);
                    //设置读取超时时间（毫秒）
                    connection.setReadTimeout(5000);

                    //返回输入流
                    InputStream in = connection.getInputStream();
                    //读取输入流
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {//关闭连接
                        connection.disconnect();
                    }
                }
            }
        }).start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(ENV.retrunTime*1000);//休眠10秒后将应用切换至前台
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //切换应用到前台
                /**获取ActivityManager*/
                ActivityManager activityManager = (ActivityManager) ENV.context.getSystemService(ACTIVITY_SERVICE);

                /**获得当前运行的task(任务)*/
                List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
                for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                    /**找到本应用的 task，并将它切换到前台*/
                    if (taskInfo.topActivity.getPackageName().equals(ENV.context.getPackageName())) {
                        activityManager.moveTaskToFront(taskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                        break;
                    }
                }
            }
        }.start();
        ENV.context.startService(ENV.intent);
    }
}
